import axios from 'axios';
import qs from 'qs';
import axiosAdapterUniapp from 'axios-adapter-uniapp'
import vStore from '../store'

let loading;
let isloading = true;
//let host = '192.168.0.105:8080' // 本地环境
//let host = '129.211.210.224:8201' // 线上环境
let host = 'dev-api-cdp.hobon.cc'
let env = "prod-api"; // stage-api 测试环境 /   prod-api 生产环境
function initEnv(version) {
	console.log('当前环境: ' + version)
	switch (version) {
		case 'develop': // 开发版（开发环境）
			env = "dev-api"
			break
		case 'trial': // 体验版（被选择为体验版的版本：测试环境）
			env = "stage-api"
			break
		case 'release': // 正式版（审核通过，发布上线后的版本：正式环境）
		default:
			env = "prod-api"
			break

	}
}
if (typeof __wxConfig == 'object') {
	let version = __wxConfig.envVersion
	initEnv(version)
}
//let baseUrl = `https://${host}`; //生产环境
//let baseUrl = `https://${host}`; //生产环境
let uploadUrlDC = `https://dc.hobon.cc/`;
let uploadUrlSM = `https://cdpnomal.hobon.cc/`;
let socketUrl = `wss://${host}/${env}/socket`;
let baseUrl = function() {
	let url = '';
	if (uni.getStorageSync('environment') === 'D') {
		url = `https://dev-api-cdp.hobon.cc`
	} else if (uni.getStorageSync('environment') === 'T') {
		url = `https://dev-api-cdp.hobon.cc`
	} else {
		url = `https://api-cdp.hobon.cc`
	}
	return url;
}; //生产环境

const instance = axios.create({
	adapter: axiosAdapterUniapp,
	timeout: 120000, // request timeout
});

//http request 拦截器  
instance.interceptors.request.use(config => {
		if (isloading) {
			uni.showLoading({
				title: '加载中'
			});
			loading = true;
		}
		var cookie = uni.getStorageSync('AppToken');
		//config.headers['x-requested-width'] = 'XMLHttpRequest';
		config.headers['Authorization'] = cookie;
		if (!config.data) return config;
		if (config.method === 'get') {
			// console.log('qs1', qs.stringify(config.data))
			// console.log('qs2', decodeURIComponent(qs.stringify(config.data)))
			config.url += `?${qs.stringify(config.data,{arrayFormat: 'repeat'})}`
		} else if (config.data.isUpload) {
			config.headers['Content-Type'] = 'multipart/form-data';
		} else if (config.data.formData) {
			config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
			config.data = qs.stringify(config.data);
		}
		// console.log(config.data)//如果是非上传类型 则 将数据重新组装  

		return config;
	},
	error => {
		console.log(error);
		return Promise.reject(error);
	});

//http response 拦截器  
instance.interceptors.response.use(response => {
		if (loading) {
			uni.hideLoading();
			loading = false;
		}
		var data = response.data;
		//console.log(data,'data')
		if (data.hasOwnProperty('code')) {
			if (data.code == 401) { //接口授权码无效
				//let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				//let curRoute = routes[routes.length - 1].route;
				//vStore.commit('setToken', '');
				// uni.showToast({
				// 	title: '当前账号登录已失效,请重新登录！',
				// 	icon: 'none'
				// })
				if (uni.getStorageSync('AppToken')) {
					uni.showModal({
						title: '',
						content: '当前账号登录已失效,请重新登录！',
						showCancel: false,
						complete: () => {
							uni.reLaunch({
								url: '/pages/login/index'
							})
						}
					})
					vStore.commit('setToken', '');
				}
				// if(curRoute !== 'pages/login/login'){
				// 	uni.navigateTo({url:'/pages/login/login'})
				// }
				return
			}
			if (data.code === 405) {
				uni.setStorageSync("token", "");
				vStore.commit('setToken', '');
				uni.showToast({
					title: '您的账号已在别处登录，当前已退出',
					icon: 'none'
				})
				return
			}
			if (data.code === 406) {
				uni.setStorageSync("token", "");
				vStore.commit('setToken', '');
				uni.showToast({
					title: '您当前已被离职，当前已退出',
					icon: 'none'
				})
				return
			}
			if (data.code == 500) { //服务端异常  
				uni.showToast({
					title: data.msg || "网络拥堵，请稍后再试！",
					icon: 'none',
					duration: 2000
				})
			}
			if (data.code == 501) { //服务端异常
				uni.showModal({
					title: '提示',
					content: data.msg || "网络拥堵，请稍后再试！",
					showCancel: false
				})
			}
			// if (data.code == 0) { //失败  
			//    // tools.msg(data.msg, '错误');  
			//     return;  
			// }  
		}

		return response;
	},
	error => {
		uni.hideLoading();
		console.log(error)
		// if (error.response.status === 401) {  
		//     if (loading) {  
		//         loading=false;  
		//     }  
		//   //  global.tools.notice("无权访问!", "错误");  
		//     return uni.navigateTo({url:'../pages/Login'}) //global.$router.push('/Login');  
		// } else {  
		//     return Promise.reject(error)  
		// }  
	});

//真机获取  

// axios.defaults.adapter = function(config) {
// 	 return new Promise((resolve, reject) => {
// 			var settle = require('axios/lib/core/settle');
// 			var buildURL = require('axios/lib/helpers/buildURL');
// 			var buildFullPath = require('axios/lib/core/buildFullPath');
// 			let fullurl = buildFullPath(config.baseURL,config.url)
// 			uni.request({
// 				method: config.method.toUpperCase(),
// 				url: buildURL(fullurl, config.params, config.paramsSerializer),
// 				header: config.headers,
// 				data: config.data,
// 				dataType: config.dataType,
// 				responseType: config.responseType,
// 				sslVerify: config.sslVerify,
// 				complete:function complete(response){
// 					response = {
// 					  data: response.data,
// 					  status: response.statusCode,
// 					  errMsg: response.errMsg,
// 					  header: response.header,
// 					  config: config
// 					};

// 				settle(resolve, reject, response);
// 				}
// 			})
// 	    })
// }


//axios.defaults = axiosAdapterUniapp;

/**  
 * 封装get方法  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param headers 头部信息  
 * @returns {Promise}  
 */
const get = (url, data = {}, loading = true, config = {}) => {
	isloading = loading;
	url = baseUrl() + url;
	let text = `请求地址：${url},token：${uni.getStorageSync("AppToken")},请参求数:${JSON.stringify(data)},`
	console.log(text)
	//console.log("data",data)
	config.data = data
	return new Promise((resolve, reject) => {
		instance.get(url, config)
			.then(response => {
				text += `请求返回：${JSON.stringify(response)}`;
				// uni.setClipboardData({
				//     data: text, 
				// 	showToast:false,
				//     success: function () {
				// 		if(response.data.code==500){
				// 			uni.showToast({
				// 				title:response.data.msg || "网络拥堵，请稍后再试！",
				// 				icon:"none"
				// 			})
				// 		}else{
				// 			uni.hideToast();
				// 		}
				//     }
				// })
				resolve(response.data);
			})
			.catch(err => {
				console.log(err)
				resolve({
					code: 500
				})
			})
	})
}

/**  
 * 封装post请求  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param config config信息  
 * @returns {Promise}  
 */
const post = (url, data = {}, loading = true, config = {}) => {
	isloading = loading;
	url = baseUrl() + url;
	let text = `请求地址：${url},token：${uni.getStorageSync("AppToken")},请参求数:${JSON.stringify(data)},`
	console.log(text)
	console.log("data", data)
	return new Promise((resolve, reject) => {
		instance.post(url, data, config)
			.then(response => {
				text += `请求返回：${JSON.stringify(response.data)}`;
				// uni.setClipboardData({
				//     data: text, 
				// 	showToast:false,
				//     success: function () {
				// 		if(response.data.code==500){
				// 			uni.showToast({
				// 				title:response.data.msg || "网络拥堵，请稍后再试！",
				// 				icon:"none"
				// 			})
				// 		}else{
				// 			uni.hideToast();
				// 		}
				//     }
				// })
				if (response != undefined) {
					resolve(response.data);
				}
			}, err => {
				reject(err)
			})
	})
}


/**  
 * 封装delete请求  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param config config信息  
 * @returns {Promise}  
 */
const del = (url, data = {}, loading = true, config = {}) => {
	isloading = loading;
	url = baseUrl() + url;
	return new Promise((resolve, reject) => {
		instance({
			method: "delete",
			url: url,
			data: data
		}).then(response => {
			if (response != undefined) {
				resolve(response.data);
			}
		}, err => {
			reject(err)
		})
	})
}

/**  
 * 封装 post 请求 用于上传文件   
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param config config信息  
 * @returns {Promise}  
 */
export function upload(url, data = {}, loading = true, config = {}) {
	isloading = loading;
	if (!data) data = {};
	data.isUpload = true;
	return new Promise((resolve, reject) => {
		instance.post(url, data, config)
			.then(response => {
				if (response != undefined) {
					resolve(response);
				}
			}, err => {
				reject(err)
			})
	})
}

/**  
 * 封装 get请求 用于下载文件  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @returns {Promise}  
 */
export function download(url, data = {}, loading = true) {
	this.get(url, data, loading, {
		// responseType: 'stream',  
		responseType: 'blob',
		// responseType: 'arraybuffer',  
	}).then(res => {
		var data = res.data;
		var headers = res.headers;
		//"attachment; filename=6a9c13bc-e214-44e4-8456-dbca9fcd2367.xls;filename*=UTF-8''6a9c13bc-e214-44e4-8456-dbca9fcd2367.xls"  
		var contentDisposition = headers['content-disposition'];
		var contentType = headers['content-type'];
		var attachmentInfoArrary = contentDisposition.split(';');
		var fileName = '';
		if (attachmentInfoArrary.length > 1) {
			fileName = attachmentInfoArrary[1].split('=')[1];
		}
		var blob = new Blob([data], {
			type: contentType
		});

		if (window.navigator && window.navigator.msSaveOrOpenBlob) { // IE  
			window.navigator.msSaveOrOpenBlob(blob, fileName);
		} else {
			let url = (window.URL || window.webkitURL).createObjectURL(blob);
			// window.open(url, "_blank"); //下载  
			// window.URL.revokeObjectURL(url) // 只要映射存在，Blob就不能进行垃圾回收，因此一旦不再需要引用，就必须小心撤销URL，释放掉blob对象。  

			let a = document.createElement('a');
			a.style.display = 'none';
			a.href = url;
			a.setAttribute('download', fileName);
			document.body.appendChild(a);
			a.click()
			document.body.removeChild(a); // 下载完成移除元素  
			// window.location.href = url  
			window.URL.revokeObjectURL(url); // 只要映射存在，Blob就不能进行垃圾回收，因此一旦不再需要引用，就必须小心撤销URL，释放掉blob对象。  

		}
	});
}

/**  
 * 封装patch请求  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param config config信息  
 * @returns {Promise}  
 */
const patch = (url, data = {}, loading = true, config = {}) => {
	isloading = loading;
	data.authToken = uni.getStorageSync("token");
	data.validParam = uni.getStorageSync("user");
	url = `${url}?${qs.stringify(data)}`;
	url = baseUrl() + url;
	return new Promise((resolve, reject) => {
		instance({
				method: "patch",
				url: url,
				data: data
			})
			.then(response => {
				if (response != undefined) {
					resolve(response.data);
				}
			}, err => {
				reject(err)
			})
	})
}

/**  
 * 封装put请求  
 * @param url  
 * @param data  
 * @param loading 是否有加载效果  
 * @param config config信息  
 * @returns {Promise}  
 */
const put = (url, data = {}, loading = true, config = {}) => {
	isloading = loading;
	url = baseUrl() + url;
	let text = `请求地址：${url},token：${uni.getStorageSync("AppToken")},请参求数:${JSON.stringify(data)},`
	console.log(text)
	return new Promise((resolve, reject) => {
		instance.put(url, data, config)
			.then(response => {
				if (response != undefined) {
					resolve(response.data);
				}
			}, err => {
				reject(err)
			})
	})
}

export const __ENV = {
	develop: 'develop',
	trial: 'trial',
	release: 'release'
}

/**
 * @param {__ENV.release} version
 */
export function SwitchEnv(version) {
	console.log(version)
	if (typeof __wxConfig == 'object') {
		if (__wxConfig.envVersion != __ENV.release) {
			initEnv(version)
		}
	}
}

export default {
	get,
	post,
	del,
	patch,
	put,
	uploadUrlSM,
	uploadUrlDC,
	socketUrl,
	env
}